package com.yu.config;

import com.yu.security.CustomUserService;
import com.yu.service.MyFilterSecurityInterceptor;
import com.yu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

import javax.annotation.Resource;

/**
 * @Description: TODO
 * @Author : yu
 * Date : 4/21/2020 2:31 PM
 */
//aop：横切，我们没有修改源代码，而是切进去
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UserService userService;

    @Resource
    private MyFilterSecurityInterceptor myFilterSecurityInterceptor;



    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        //首页所有人可以访问，功能页只有特定的身份可以访问
        //请求授权的规则
//        http.authorizeRequests().antMatchers("/","/user/login","css/*","js/**","img/**","index.html").permitAll()
//                .antMatchers("/level1/**").hasRole("")
//                .antMatchers("/level2/**").hasRole("admin")
//                .antMatchers("/level3/**").hasRole("admin");
        //没有权限会默认到登录页面,需要开启登录页面
//        http.formLogin().defaultSuccessUrl("/");
//
//        //注销
//        http.logout().logoutSuccessUrl("/");
        http.authorizeRequests().antMatchers("/","/user/login","css/*","js/**","img/**","index.html").permitAll()
                .anyRequest().authenticated() //任何请求,登录后可以访问
                .and()
                .formLogin()
                .loginPage("/toLogin")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/")
                .failureUrl("/login?error")
                .permitAll() //登录页面用户任意访问
                .and()
                .logout().permitAll(); //注销行为任意访问
        //添加一个拦截器
        http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);
        //防止网站工具:get post
        //关闭跨网点攻击
        //http.csrf().disable();
        //记住我功能
        http.csrf().disable();
        http.rememberMe();

    }

    //springboot 2.1.x可以直接使用
    //密码编译:new BCryptPasswordEncoder().encode("123456")
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
    }
}
